<template>
    <div class="MyInfo-container">
        <el-row>
            <el-col :span="24">
                <el-row :gutter="20">
                    <el-col :span="3">
                        <el-row>
                            <el-col>
                                <div class="avatar">
                                    <img :src="userAvatar" alt="">
                                </div>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col style="text-align: center">
                                <el-button @click="handleEditAvatar">编辑头像</el-button>
                            </el-col>
                        </el-row>
                    </el-col>


                    <el-col :span="21">
                        <el-row>
                            <el-col>
                                <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                                    <el-form-item label="用户姓名：" prop="realName">
                                        <el-input v-model="form.realName" style="width: 306px;"></el-input>
                                    </el-form-item>

                                    <el-form-item label="邮箱地址：" prop="email">
                                        <el-input v-model="form.email" style="width: 306px;"></el-input>
                                    </el-form-item>

                                    <el-form-item label="手机号码：" prop="mobile">
                                        <div class="mobile">
                                            <el-input v-model="form.mobile" style="width: 190px;"></el-input>

                                            <el-button @click="getIdentifyCode" :disabled="canGetIdentifyCode" style="background: #f7f7f7; color: #495060">{{gettingIdentifyCodeBtnContent}}</el-button>
                                            <div class="inputCode" v-show="inputCodeVisible">
                                                <div class="wrapper">
                                                    <el-input v-model="securityCode" placeholder="请填写短信验证码"></el-input>
                                                    <div class="margin-top-10">
                                                        <el-button @click="inputCodeVisible=false">取消</el-button>
                                                        <el-button type="primary">保存</el-button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </el-form-item>

                                    <el-form-item label="账号：">
                                        {{ user.account }}
                                    </el-form-item>
                                    <el-form-item label="密码：">
                                        <el-button type="text" @click="dialogEditPassVisible = true">修改密码</el-button>
                                    </el-form-item>

                                    <el-form-item label="角色：">
                                        <template v-for="item in user.roles">
                                            <el-tag type="primary" size="small">{{ item }}</el-tag>
                                        </template>
                                    </el-form-item>
                                    <el-form-item label="群组：">
                                        <template v-for="item in user.groups">
                                            <el-tag type="primary" size="small">{{ item }}</el-tag>
                                        </template>
                                    </el-form-item>
                                    <el-form-item label="部门：">
                                        <template v-for="(item, index) in user.department">
                                            <el-tag type="primary" size="small">{{ item.name }}</el-tag>
                                        </template>
                                    </el-form-item>
                                    <el-form-item label="公司：">
                                        <template v-for="(item, index) in user.company">
                                            <el-tag type="primary" size="small">{{ item.name }}</el-tag>
                                        </template>
                                    </el-form-item>


                                </el-form>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col>
                                <el-button>取消</el-button>
                                <el-button type="primary" @click="updateInfo">保存</el-button>
                            </el-col>
                        </el-row>

                    </el-col>
                </el-row>
            </el-col>
        </el-row>

        <el-dialog title="修改密码" :visible.sync="dialogEditPassVisible" :close-on-press-escape="false" :close-on-click-modal="false"  @close="handleCloseDialog">
            <el-form :model="editPasswordForm" :rules="editPasswordRules" ref="editPasswordForm" labelPosition="right" labelWidth="100px" style="width: 400px">
                <el-form-item label="原密码" prop="oldPassword">
                    <el-input v-model="editPasswordForm.oldPassword"></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                    <el-input v-model="editPasswordForm.newPassword"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="rePass">
                    <el-input v-model="editPasswordForm.rePass"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogEditPassVisible = false">取 消</el-button>
                <el-button type="primary" @click="updatePassword">确 定</el-button>
            </div>
        </el-dialog>


        <el-dialog title="编辑头像" width="40.5%" :visible.sync="dialogEditAvatarVisible" :close-on-press-escape="false" :close-on-click-modal="false">

            <div class="edit-avatar-box">
                <div class="avatar-cropper">
                    <img id="image" :src="picture" alt="图片预览" v-show="picture !== ''">
                </div>
                <div class="cropper-preview"></div>
                <div class="upload-button">
                    <file-upload
                            class="el-button el-button--primary"
                            :post-action="uploadAction"
                            :multiple="false"
                            :drop="true"
                            :drop-directory="true"
                            v-model="files"
                            @input-filter="inputFilter"
                            @input-file="inputFile"
                            ref="upload">
                        <i class="el-icon-picture"></i> 选择图片
                    </file-upload>

                    <el-button class="start-upload" type="primary" icon="el-icon-upload"
                               :disabled="(!$refs.upload || !$refs.upload.active ? false : true)"
                               @click.prevent="$refs.upload.active = true">
                        上传头像
                    </el-button>

                    <template v-for="file in files">
                        <el-progress style="margin-top: 6px; width: 243px;"
                                     v-if="file.active || file.progress !== '0.00'"
                                     :text-inside="true"
                                     :stroke-width="18"
                                     :percentage="parseInt(file.progress)">
                        </el-progress>
                        <span v-if="file.error" style="color: #FA5555">{{file.error}}</span>
                        <span v-else-if="file.success" style="color: #67C23A">头像上传成功</span>
                        <span v-else-if="file.active" style="color: #409EFF">上传中</span>
                        <span v-else></span>
                    </template>

                </div>

            </div>

        </el-dialog>
    </div>
</template>

<script>
    import FileUpload from 'vue-upload-component'
    import ImageCompressor from 'image-compressor'
    import { mapGetters } from 'vuex'
    import { uploadAction } from '@/api/system/oss'
    import { updatedMyInfo, updateMyPassword, updateMyAvatar } from '@/api/upms/user'
    import uAvatar from '../../../static/img/avatar/user2-160x160.jpg'
    export default {
        name: 'MyInfo',
        components: {
            FileUpload
        },
        data() {
            const validPhone = (rule, value, callback) => {
                var re = /^1[0-9]{10}$/;
                if (!re.test(value)) {
                    callback(new Error('请输入正确格式的手机号'));
                } else {
                    callback();
                }
            }
            const validRePassword = (rule, value, callback) => {
                if (value !== this.editPasswordForm.newPassword) {
                    callback(new Error('两次输入密码不一致'));
                } else {
                    callback();
                }
            }

            return {
                inputCodeVisible: false, // 显示填写验证码box
                hasGetIdentifyCode: false,  // 是否点了获取验证码
                securityCode: '',   //验证码
                gettingIdentifyCodeBtnContent: '获取验证码',  // “获取验证码”按钮的文字
                canGetIdentifyCode: false,  // 是否可点获取验证码
                dialogEditPassVisible: false, // 修改密码Dialog
                dialogEditAvatarVisible: false, // 编辑头像Dialog
                form: {
                    realName: '',
                    email: '',
                    mobile: ''
                },
                rules: {
                    realName: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ],
                    email: [
                        { required: true, message: '邮件地址不能为空', trigger: 'blur' },
                        { type: 'email', message: '邮件格式不正确', trigger: 'blur' }
                    ],
                    mobile: [
                        { required: true, message: '请输入手机号码' },
                        { validator: validPhone }
                    ]
                },
                editPasswordForm: {
                    oldPassword: '',
                    newPassword: '',
                    rePass: ''
                },
                editPasswordRules: {
                    oldPassword: [
                        { required: true, message: '请输入原密码', trigger: 'blur' }
                    ],
                    newPassword: [
                        { required: true, message: '请输入新密码', trigger: 'blur' },
                        { min: 6, message: '请至少输入6个字符', trigger: 'blur' },
                        { max: 32, message: '最多输入32个字符', trigger: 'blur' }
                    ],
                    rePass: [
                        { required: true, message: '请再次输入新密码', trigger: 'blur' },
                        { validator: validRePassword, trigger: 'blur' }
                    ]
                },

                userAvatar: '',

                picture: '',

                files: [],
                uploadAuto: false,
                uploadAction: uploadAction,
                autoCompress: 1024 * 1024 * 2,
                size: 1024 * 1024 * 2,
            }
        },
        computed: {
            ...mapGetters(['user', 'ipCity'])
        },
        methods: {
            inputFilter(newFile, oldFile, prevent) {
                if (newFile && !oldFile) {
                    // 添加文件前
                    // 过滤系统文件 和隐藏文件
                    if (/(\/|^)(Thumbs\.db|desktop\.ini|\..+)$/.test(newFile.name)) {
                        return prevent()
                    }
                    // 过滤 php html js 文件
                    if (/\.(php5?|html?|jsx?)$/i.test(newFile.name)) {
                        return prevent()
                    }

                    // 自动压缩
                    if (newFile.file && newFile.type.substr(0, 6) === 'image/' && this.autoCompress > 0 && this.autoCompress < newFile.size) {
                        newFile.error = 'compressing'
                        const imageCompressor = new ImageCompressor(null, {
                            convertSize: Infinity,
                            maxWidth: 512,
                            maxHeight: 512,
                        })
                        imageCompressor.compress(newFile.file)
                            .then((file) => {
                                this.$refs.upload.update(newFile, { error: '', file, size: file.size, type: file.type })
                            })
                            .catch((err) => {
                                this.$refs.upload.update(newFile, { error: err.message || 'compress' })
                            })
                    }

                    if (newFile && (!oldFile || newFile.file !== oldFile.file)) {
                        // 创建 blob 字段
                        newFile.blob = ''
                        let URL = window.URL || window.webkitURL
                        if (URL && URL.createObjectURL) {
                            newFile.blob = URL.createObjectURL(newFile.file)
                        }
                        // 缩略图
                        newFile.thumb = ''
                        if (newFile.blob && newFile.type.substr(0, 6) === 'image/') {
                            newFile.thumb = newFile.blob
                            this.picture = newFile.thumb
                        }
                    }
                }
            },
            inputFile(newFile, oldFile) {
                if (newFile && !oldFile) {
                    // 添加文件
                }

                if (newFile && oldFile) {
                    // 更新文件

                    // 开始上传
                    if (newFile.active && !oldFile.active) {
                        // beforeSend
                        //设置每个文件携带的参数
                        newFile.data = Object.assign({}, {
                            'ossName': 'qiniuyun',
                            'bucketName': 'test',   //空间名称
                            'prefixName': 'avatar'
                        })
                        // 限定最小字节
                        if (newFile.size >= 0 && this.minSize > 0 && newFile.size < this.minSize) {
                            this.$refs.upload.update(newFile, { error: 'size' })
                        }
                    }
                    // 上传进度
                    if (newFile.progress !== oldFile.progress) {
                        //console.log('progress', newFile.progress, newFile)
                    }
                    // 上传错误
                    if (newFile.error !== oldFile.error) {
                        //console.log('error', newFile.error, newFile)
                    }
                    // 上传成功
                    if (newFile.success !== oldFile.success) {
                        const response = newFile.response ;
                        if(response.status) {
                            const data = {'id': this.user.id, 'avatar': response.url}
                            updateMyAvatar(data).then(res => {
                                if(res.data.status) {
                                    this.$notify({
                                        title: '头像编辑成功', message: res.data.message,
                                        type: 'success', duration: 2000
                                    })
                                    setTimeout(()=>{
                                        this.dialogEditAvatarVisible = false
                                    }, 500)
                                } else {
                                    this.$notify({
                                        title: '发生错误', message: res.data.message,
                                        type: 'error', duration: 2000
                                    })
                                }
                            })
                        }

                    }
                }

                if (!newFile && oldFile) {
                    // 删除文件
                    // 自动删除 服务器上的文件
                    if (oldFile.success && oldFile.response.id) {
                        // $.ajax({
                        //   type: 'DELETE',
                        //   url: '/file/delete?id=' + oldFile.response.id,
                        // });
                    }
                }

                // 自动上传
                if (Boolean(newFile) !== Boolean(oldFile) || oldFile.error !== newFile.error) {
                    if (this.uploadAuto && !this.$refs.upload.active) {
                        this.$refs.upload.active = true
                    }
                }
            },
            handleEditAvatar() {
                this.dialogEditAvatarVisible = true
            },
            handleCloseDialog() {
                this.resetEditPasswordForm()
            },
            getIdentifyCode() {
                this.hasGetIdentifyCode = true
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        this.canGetIdentifyCode = true;
                        let timeLast = 60;
                        let timer = setInterval(() => {
                            if (timeLast >= 0) {
                                this.gettingIdentifyCodeBtnContent = timeLast + '秒后重试';
                                timeLast -= 1;
                            } else {
                                clearInterval(timer);
                                this.gettingIdentifyCodeBtnContent = '获取验证码';
                                this.canGetIdentifyCode = false;
                            }
                        }, 1000);
                        this.inputCodeVisible = true;
                        // you can write ajax request here
                    }
                })
            },
            updateInfo() {  //修改信息
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        updatedMyInfo(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                            } else {
                                this.$notify({
                                    title: '错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                        }).catch((error)=>{
                            console.log(error)
                        })
                    }
                })
            },
            updatePassword() { //修改密码
                this.$refs['editPasswordForm'].validate((valid) => {
                    if (valid) {
                        updateMyPassword(this.editPasswordForm).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.dialogEditPassVisible = false
                            } else {
                                this.$notify({
                                    title: '错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                        }).catch((error)=>{
                            console.log(error)
                        })
                    }
                })
            },
            resetEditPasswordForm() {
                this.$refs['editPasswordForm'].resetFields()
                this.editPasswordForm = {
                    id:this.user.id,
                    oldPassword: '',
                    newPassword: '',
                    rePass: ''
                }
            }
        },
        created() {
            this.form.id = this.user.id
            this.form.realName = this.user.realName
            this.form.email = this.user.email
            this.form.mobile = this.user.mobile
            this.editPasswordForm.id = this.user.id

            if(this.user.avatar) {
                this.userAvatar = this.user.avatar
            } else {
                this.userAvatar = uAvatar
            }
        },
        mounted: function () {
            this.$nextTick(function () {

            })
        }
    }
</script>

<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>
    .avatar{
        margin: 0 auto;
        height: 150px;
        width: 150px;
        margin-bottom: 10px;
        img{
            width: 100%;
            height: 100%;
            border-radius: 50%;
        }
    }
    .mobile{
        position: relative;
        display: block;
        width: 310px;
        .inputCode {
            position: absolute;
            top: -30px;
            right:-220px;
            width: 200px;
            height: 110px;
            border-radius: 4px;
            box-shadow: 0 0 2px 3px rgba(0,0,0,.1);
            .wrapper{
                margin: 10px;
                text-align: right;
            }
        }
    }
    .edit-avatar-box{
        height: 350px;

        .avatar-cropper{
            border: 1px solid #878D99;
            padding: 5px;
            width: 400px;
            height: 300px;
            float: left;
            margin-right: 10px;
            box-sizing: border-box;
            img{
                max-width: 100%;
            }
        }
        .cropper-preview{
            border: 1px solid #878D99;
            width: 320px;
            height: 200px;
            float: left;
            box-sizing: border-box;
        }
        .upload-button{
            box-sizing: border-box;
            float: left;
            position: relative;
            width: 320px;
            height: 90px;
            margin-top: 10px;
            label.file-uploads{
                position: absolute;
            }
            .start-upload{
                margin-left: 120px;
            }
        }
    }
</style>